package com.yxq.mdt.app.modules.socialcontact.ui.fragment.main;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseFragment;
import com.yxq.mdt.app.model.ShareBean;
import com.yxq.mdt.app.modules.bottomsheet.ShareSheetDialog;
import com.yxq.mdt.app.modules.socialcontact.adapter.MainSocialContactRecommendAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.MainSocialContactRecommendBean;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialRecommendContract;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialRecommendPresenter;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.CircleTheHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialPersonalHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialStateDetailsAc;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.MediaPlayerHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.jzvd.Jzvd;

/**
 * 社区推荐
 */
public class RecommendFragment extends BaseFragment<MainSocialRecommendPresenter> implements MainSocialRecommendContract.View {
    @BindView(R.id.social_state_recyclerView)
    RecyclerView socialStateRecyclerView;
    MainSocialContactRecommendAdapter mainSocialContactRecommendAdapter;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private List<MainSocialContactRecommendBean.ListBean> mainSocialContactRecommendBeans;

    @Override
    protected int attachLayoutId() {
        setImmersionBarEnabled(false);
        return R.layout.fragment_social_recommend;
    }

    @Override
    protected MainSocialRecommendPresenter getPresenter() {
        return new MainSocialRecommendPresenter(this, new MainSocialContactModel());
    }


    @Override
    public void initView(View view) {
        mainSocialContactRecommendBeans = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setStackFromEnd(true);
        socialStateRecyclerView.setLayoutManager(linearLayoutManager);
        mainSocialContactRecommendAdapter = new MainSocialContactRecommendAdapter(R.layout.item_layout_dynamic_list, mainSocialContactRecommendBeans);
        socialStateRecyclerView.setAdapter(mainSocialContactRecommendAdapter);
        mainSocialContactRecommendAdapter.setOnItemClickListener((adapter, view1, position) -> {
            if (mainSocialContactRecommendAdapter.countDownTimer != null) {
                mainSocialContactRecommendAdapter.countDownTimer.onFinish();
                Jzvd.releaseAllVideos();
                MediaPlayerHelper.realese();
            }
            Intent it = new Intent(mContext, SocialStateDetailsAc.class);
            if (mainSocialContactRecommendAdapter.getItem(0).getId() != null) {
                it.putExtra("topicId", mainSocialContactRecommendAdapter.getItem(position).getId());
                it.putExtra("id", mainSocialContactRecommendAdapter.getItem(position).getId());
                startActivity(it);
            } else {
                it.putExtra("topicId", mainSocialContactRecommendAdapter.getItem(position).getId());
                it.putExtra("id", mainSocialContactRecommendAdapter.getItem(position).getId());
                startActivity(it);
            }

        });
        mainSocialContactRecommendAdapter.setOnItemChildClickListener((adapter, view12, position) -> {
            switch (view12.getId()) {
                case R.id.item_layout_nike_img:
                    if (mainSocialContactRecommendAdapter.countDownTimer != null) {
                        mainSocialContactRecommendAdapter.countDownTimer.onFinish();
                        Jzvd.releaseAllVideos();
                        MediaPlayerHelper.realese();
                    }
                    Intent intent = new Intent(mContext, SocialPersonalHomepageAc.class);
                    intent.putExtra("userId", mainSocialContactRecommendAdapter.getItem(position).getCreateMan());
                    intent.putExtra("name", mainSocialContactRecommendAdapter.getItem(position).getGsName());
                    startActivity(intent);

                    break;
                case R.id.item_layout_content_browse:
                case R.id.item_layout_content_browse_img:
                case R.id.item_layout_content_browse_lint:
                    int giveNum = mainSocialContactRecommendAdapter.getItem(position).getUpCount();
                    if (mainSocialContactRecommendAdapter.getItem(position).getGiveLike() != 0) {
                        MainSocialContactModel.delGsTopicFavour("2", mainSocialContactRecommendAdapter.getItem(position).getId(), new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                showCenterToast("取消点赞成功");
                                mainSocialContactRecommendAdapter.getItem(position).setGiveLike(0);
                                mainSocialContactRecommendAdapter.getItem(position).setUpCount(giveNum - 1);
                                mainSocialContactRecommendAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("取消点赞失败");
                            }
                        });
                    } else {
                        MainSocialContactModel.saveGsTopicFavour(mainSocialContactRecommendAdapter.getItem(position).getId(), "2", new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                showCenterToast("点赞成功");
                                mainSocialContactRecommendAdapter.getItem(position).setGiveLike(1);
                                mainSocialContactRecommendAdapter.getItem(position).setUpCount(giveNum + 1);
                                mainSocialContactRecommendAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("点赞失败");
                            }
                        });
                    }
                    break;
                case R.id.item_layout_attention:
                    TextView attention = view12.findViewById(R.id.item_layout_attention);
                    MainSocialContactModel.setInterestRelation(mainSocialContactRecommendAdapter.getItem(position).getUserId() + "", 1, 1, new ApiModel.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            for (MainSocialContactRecommendBean.ListBean socialContactRecommendBean : mainSocialContactRecommendAdapter.getData()) {
                                if (socialContactRecommendBean.getUserId() == mainSocialContactRecommendAdapter.getItem(position).getUserId()) {
                                    socialContactRecommendBean.setRelationNum(1);
                                    mainSocialContactRecommendAdapter.notifyDataSetChanged();
                                }
                            }
                            attention.setVisibility(View.GONE);
                            showCenterToast("关注成功");

                        }

                        @Override
                        public void onError(String errMsg) {
                            showCenterToast("关注失败");
                        }
                    });
                    break;
                case R.id.group_lint:
                    if (mainSocialContactRecommendAdapter.countDownTimer != null) {
                        mainSocialContactRecommendAdapter.countDownTimer.onFinish();
                    }
                    Jzvd.releaseAllVideos();
                    MediaPlayerHelper.realese();
                    Intent it = new Intent(mContext, CircleTheHomepageAc.class);
                    it.putExtra("id", mainSocialContactRecommendAdapter.getItem(position).getGroupId());
                    it.putExtra("CircleName", mainSocialContactRecommendAdapter.getItem(position).getGsName());
                    startActivity(it);
                    break;
                case R.id.item_tv_subject:
                    if (mainSocialContactRecommendAdapter.countDownTimer != null) {
                        mainSocialContactRecommendAdapter.countDownTimer.onFinish();
                        Jzvd.releaseAllVideos();
                        MediaPlayerHelper.realese();
                    }
                    Intent goIt = new Intent(mContext, SocialStateDetailsAc.class);
                    if (mainSocialContactRecommendAdapter.getItem(0).getId() != null) {
                        goIt.putExtra("topicId", mainSocialContactRecommendAdapter.getItem(position).getId());
                        goIt.putExtra("id", mainSocialContactRecommendAdapter.getItem(position).getId());
                        startActivity(goIt);
                    } else {
                        goIt.putExtra("topicId", mainSocialContactRecommendAdapter.getItem(position).getId());
                        goIt.putExtra("id", mainSocialContactRecommendAdapter.getItem(position).getId());
                        startActivity(goIt);
                    }
                    break;
                case R.id.item_layout_content_share:
                    //分享
                    ShareBean shareBean = new ShareBean();

                    if (!TextUtils.isEmpty(mainSocialContactRecommendAdapter.getItem(position).getContent())) {
                        shareBean.setTitle(mainSocialContactRecommendAdapter.getItem(position).getContent());//文本
                        shareBean.setText(mainSocialContactRecommendAdapter.getItem(position).getContent());//文本
                    } else {
                        shareBean.setTitle("社交电商新玩法，好玩让你意想不到。");//文本
                        shareBean.setText("社交电商新玩法，好玩让你意想不到。");//文本
                    }
                    shareBean.setShareType("0");//图文分享
                    shareBean.setShareTypeAPP(2);
                    shareBean.setHandleId(mainSocialContactRecommendAdapter.getItem(position).getId());
                    if (mainSocialContactRecommendAdapter.getItem(position).getFileList() != null && mainSocialContactRecommendAdapter.getItem(position).getFileList().size() > 0 && "1".equals(mainSocialContactRecommendAdapter.getItem(position).getFileList().get(0).getClass1())) {
                        shareBean.setImageUrl(mainSocialContactRecommendAdapter.getItem(position).getFileList().get(0).getFile());//LOGO
                    } else {
                        shareBean.setImageUrl("https://yxqoss.oss-cn-hangzhou.aliyuncs.com/gs_app/init/727c432c9e186a11.png");//LOGO
                    }
                    if (!"release".equals(BuildConfig.RELEASE)) {
                        shareBean.setUrl("http://testpm.quai69.com/webtrends.html?topicId=" + mainSocialContactRecommendAdapter.getItem(position).getId() + "&platform=2&parent_id=" + getParentId());//分享URL
                    } else {
                        shareBean.setUrl("http://pm.quai69.com/webtrends.html?topicId=" + mainSocialContactRecommendAdapter.getItem(position).getId() + "&platform=2&parent_id=" + getParentId());
                    }
                    ShareSheetDialog shareSheetDialog = new ShareSheetDialog(shareBean, false);
                    shareSheetDialog.show(getChildFragmentManager(), "shareSheetDialog");
                    break;
                default:
            }
        });
        socialStateRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {
            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                try {
                    Jzvd jzvd = view.findViewById(R.id.item_social_video_player);
                    if (jzvd != null && Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.jzDataSource != null && Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl() != null) {
                        if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                            if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                                Jzvd.releaseAllVideos();
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (mainSocialContactRecommendAdapter.countDownTimer != null) {
                    mainSocialContactRecommendAdapter.countDownTimer.onFinish();
                    MediaPlayerHelper.pause();
                }
            }
        });
        socialStateRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mainSocialContactRecommendAdapter.countDownTimer != null) {
                    mainSocialContactRecommendAdapter.countDownTimer.onFinish();
                    MediaPlayerHelper.pause();
                }
            }
        });
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getRecommendList(1, 20);
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            page++;
            mPresenter.getRecommendList(page, 20);
        });
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableAutoLoadMore(true);
    }

    public void loadMore() {
        page++;
        mPresenter.getRecommendList(page, 30);
    }

    @Override
    public void initData() {
//        loadCache();
    }

    /**
     * 预加载缓存数据
     */
    private void loadCache() {
        String recommendStr = Hawk.get("sc-recommend", null);
        //推荐列表数据
        if (recommendStr != null) {
            MainSocialContactRecommendBean mainSocialContactRecommendBean = JSON.parseObject(recommendStr, MainSocialContactRecommendBean.class);
            onLoadRecommendListSuccess(mainSocialContactRecommendBean);
        }
    }

    public void refresh() {
        page = 1;
        mPresenter.getRecommendList(page, 30);
        mainSocialContactRecommendAdapter.setNewData(mainSocialContactRecommendBeans);
        mainSocialContactRecommendAdapter.notifyDataSetChanged();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getActivity().finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mainSocialContactRecommendAdapter.countDownTimer != null) {
            mainSocialContactRecommendAdapter.countDownTimer.onFinish();
            Jzvd.releaseAllVideos();
            MediaPlayerHelper.realese();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (mainSocialContactRecommendAdapter.countDownTimer != null) {
            mainSocialContactRecommendAdapter.countDownTimer.cancel();
        }
        Jzvd.goOnPlayOnPause();
        MediaPlayerHelper.realese();
    }

    @Override
    public void onLoadRecommendListSuccess(MainSocialContactRecommendBean mainSocialContactRecommendBean) {
        if (mainSocialContactRecommendBean != null) {
            Hawk.put("sc-recommend", JSON.toJSONString(mainSocialContactRecommendBean));
        }
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();

        if (page == 1) {
            mainSocialContactRecommendAdapter.setNewData(mainSocialContactRecommendBean.getList());
        } else {
            if (mainSocialContactRecommendBean.getList() != null && mainSocialContactRecommendBean.getList().size() != 0) {
                mainSocialContactRecommendAdapter.addData(mainSocialContactRecommendBean.getList());
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
    }

    @Override
    public void onLoadRecommendListFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void onResume() {
        super.onResume();
        mainSocialContactRecommendAdapter.notifyDataSetChanged();
    }
}
